﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AppSocketModel;
using AppSocketService.Account;
using BCGPSRESTful.WebApiConfig;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace BCGPSRESTful.Controllers.Page.Account
{
    /// <summary>
    /// 个人账户
    /// </summary>
    [ApiExplorerSettings(GroupName = "PersonPage")]
    [Route("api/[controller]")]
    [ApiController]
    public class AccountPersonController : PageBaseController
    {
        private readonly TimeSpan expiration = TimeSpan.FromDays(7);
        private readonly IAccountPersonService accountPersonService;

        #region 构造函数
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="accountPersonService"></param>
        public AccountPersonController(IAccountPersonService accountPersonService)
        {
            this.accountPersonService = accountPersonService;
 
        }
        #endregion

        #region 注册个人账户
        /// <summary>
        /// 注册个人账户
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("[action]")]
        [AllowAnonymous]
        public ActionResult<AccountDto> Register(AccountPersonRegisterDto dto)
        {
           return  accountPersonService.RegisterPersonAccount(dto);
        }
        #endregion

        #region 账户登录
        /// <summary>
        /// 账户登录
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("[action]")]
        [ProducesResponseType(typeof(TokenDto), 200)]
        [AllowAnonymous]
        public ActionResult<TokenDto> Login([FromBody] AccountLoginDto dto)
        {
            var ip = Request.Headers["X-Forwarded-For"].FirstOrDefault();
            if (string.IsNullOrWhiteSpace(ip))
                ip = HttpContext.Connection.RemoteIpAddress.ToString();

            var accountDto = accountPersonService.Login(dto, ip);

            if (accountDto == null)
                throw new ArgumentException("用户名或密码不正确!");

            return new TokenDto
            {
                Description = "WELCAME:" + accountDto.AccountCode,
                AccessToken = accountDto.GenerateToken(expiration, AccountRole.PERSON),
                ExpiresIn = (int)expiration.TotalSeconds,
                EndTime = DateTime.Now.AddSeconds(expiration.TotalSeconds - 12 * 3600)
            };
        }

        #endregion
         
        #region 注销账户 --- 已登录账户
        /// <summary>
        /// 注销账户 --- 已登录账户
        /// </summary>
        /// <returns></returns>
        [HttpDelete("[action]")] 
        public ActionResult<bool> UnRegister()
        {
            return accountPersonService.UnRegisterPersonAccount();
        }
        #endregion
    }
}